package net.lesscoding.general;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;

import java.util.concurrent.TimeUnit;

/**
 * @author eleven
 * @date 2023/9/5 22:29
 * @apiNote 异步消息发送者
 */
public class AsyncProducer {
    public static void main(String[] args) throws Exception {
        // - 创建消息生产者Producer，并指定生产者组名
        DefaultMQProducer producer = new DefaultMQProducer("group1");
        // - 指定nameServer地址
        producer.setNamesrvAddr("192.168.33.129:9876");
        // 超时时间
        producer.setSendMsgTimeout(1000000);
        // 发送失败重试三次
        producer.setRetryTimesWhenSendAsyncFailed(0);
        // - 启动producer
        producer.start();

        for (int i = 0; i < 10; i++) {
            byte[] body = ("Hi," + i).getBytes();
            Message message = new Message("TopicTest", "someTag", body);
            /**
             * firewall-cmd --zone=public --add-port=8080/tcp --permanent
             * systemctl restart firewalld
             */
            // - 发送异步消息
            producer.send(message, new SendCallback() {
                /**
                 * 发送成功回调函数
                 * @param sendResult
                 */
                @Override
                public void onSuccess(SendResult sendResult) {
                    System.out.println("发送结果：" + sendResult);
                }

                /**
                 * 发送失败回调函数
                 * @param throwable
                 */
                @Override
                public void onException(Throwable throwable) {
                    System.out.println("发送出现异常: " + throwable);
                }
            });

            TimeUnit.SECONDS.sleep(1);
        }

        // - 关闭生产者Producer
        producer.shutdown();
    }
}
